<template>
    <section class="power-add-user" @click="treeBlurHide">
        <el-form :model="userDataForm" :rules="userDataRule" ref="userDataForm" enctype="multipart/form-data" label-position="top" label-width="81px" :inline="true" class="demo-form-inline">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="账号:" prop="account">
                        <el-input :disabled="!isAdd"  v-model="userDataForm.account" size="small"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="用户名:" prop="name">
                        <el-input v-model="userDataForm.name"  size="small"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="手机号:" prop="phone">
                        <el-input v-model="userDataForm.phone" size="small"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row >
                <el-col :span="8">
                    <el-form-item label="部门:" prop="departmentId">
                        <el-input v-model="treeDepartment.departmentName" icon="caret-bottom" style="width: 192px" placeholder="请选择部门"  size="small"></el-input>
                        <div @click.stop="treeDepartment.showTree=!treeDepartment.showTree"
                             style="position: absolute;top:1px;left: 0;z-index: 10;min-width: 260px;max-width: 100%;height: 36px;">
                            <div v-show="treeDepartment.showTree" class="department-tree-select" >
                                <el-tree size="small" :data="departmentTree"
                                         :props="departmentTreeProps"
                                         :load="loadNode"
                                         @check-change="handleAddCheckChange"
                                         node-key="id" ref="addTree"
                                         check-strictly accordion
                                         highlight-current show-checkbox
                                         lazy>
                                </el-tree>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="岗位:" prop="jobId">
                        <job-select from="addUser" />
                        <!--<el-select v-model="userDataForm.departmentRoleId" placeholder="请选择角色" size="small">
                            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>-->
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="出生日期:" prop="birthday">
                        <el-date-picker v-model="userDataForm.birthday" @change="formatDate" type="date" placeholder="选择日期"  size="small"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="8">
                    <el-form-item label="性别:">
                        <el-radio-group v-model="userDataForm.sex">
                            <el-radio label="男"></el-radio>
                            <el-radio label="女"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="邮箱:" prop="email">
                        <el-input  v-model="userDataForm.email" size="small"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="QQ:">
                        <el-input  v-model="userDataForm.qq" size="small"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="简介:" style="width: 100%" >
                        <el-input style="width: 90%" v-model="userDataForm.remark" type="textarea"  :autosize="{ minRows: 5, maxRows: 8}"></el-input>
                    </el-form-item>
                </el-col>
                <!--<el-col :span="16">
                    <el-form-item label="照片:">
                        <div class="avatar-wraper " >
                            <i class="el-icon-plus"></i>
                            <div class="avatar-contain" v-if="userDataForm.userAvatar"><img  :src="userDataForm.userAvatar" class="avatar"></div>
                            <input class="uploadUserAvatar" ref="userAvatar" type="file" @change="uploadUserAvatarChange" accept="image/*">
                        </div>
                    </el-form-item>
                    <span class="upload-tips">建议大小120x120</span>
                </el-col>-->
                <el-col :span="8">

                </el-col>
            </el-row>
            <div class="add-oprate">
                <el-button class="save" @click="submitForm('userDataForm')"  type="primary" size="small"><i class="fa fa-save"></i> 保存</el-button>
                <el-button @click="exitForm('userDataForm')"  type="danger" size="small" ><i class="fa fa-sign-out"></i> 取消</el-button>
            </div>
        </el-form>
    </section>
</template>

<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios';
    import { mapGetters,mapActions,mapMutations } from 'vuex'
    import {  Row,Col,Button,Input,Select,Option,FormItem,Form,RadioGroup,Radio,DatePicker,Upload,MessageBox,Message,Tree } from 'element-ui'
    import JobSelect from '~components/jobSelect.vue'
    import {validTel,validEmail,checkQQ,getDate,returnDate,setToken} from '~/utils/auth'

    Vue.use(Row)
    Vue.use(Col)
    Vue.use(Button)
    Vue.use(Input)
    Vue.use(Select)
    Vue.use(Option)
    Vue.use(Form)
    Vue.use(FormItem)
    Vue.use(Radio)
    Vue.use(RadioGroup)
    Vue.use(DatePicker)
    Vue.use(Upload)
    Vue.use(Tree)

    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;

    export default {
        components:{
            JobSelect
        },
        validate ({ params }) {
            return (params.name === 'edit' || params.name === 'add')
        },
        data() {
            var validatePhone = (rule,value,callback) => {
                var regPhone = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/
                if(value != '' && !regPhone.test(value)) {
                    callback(new Error('请输入正确的手机号码'))
                }
            };
            var validateEmail = (rule,value,callback) => {
                var regEmail = /^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.){1,4}[a-z]{2,3}$/
                if (value != '' && !regEmail.test(value)) {
                    callback(new Error('请输入正确的邮箱地址'))
                }
            };
            return {
                userDataForm: {
                },
                userDataRule: {
                    account: [
                        { required: true, message: '请输入账号', trigger: 'blur' }
                    ],
                    name: [
                        { required: true,message: '请输入真实姓名',trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' }
                    ],
                    departmentId: [
                        { required: true, message: '请选择部门'}
                    ],
                    jobId: [
                        { required: true, message: '请选择岗位'}
                    ],
                    birthday: [
                        { required: true, message: '请选择出生日期'}
                    ]
                },
                departmentTree: [],
                departmentTreeProps: {
                    label: 'name',
                    children: 'zones'
                },
                treeDepartment: {
                    departmentName: '',
                    showTree: false
                },
                oprateName: ''
            };
        },
        computed: {
            ...mapGetters({
                userDatas: "getUserDatas",
                editIndex: "getEditIndex",
                departmentList: "getDepartmentList",
                roleList: "getRoleList",
                axiosCode: "getAxiosCode",
                pageTabsList: 'getPageTabsList'
            }),
            isAdd() {
                return this.oprateName === 'add'
            }
        },
        methods: {
            ...mapMutations([
                'dealAxiosCode'
            ]),
            ...mapActions([
                'fetchUserDatas',
                'fetchDepartmentList',
                'addNewUserControl',
                'editUserData',
                'validNewUser',
                'userPhotoUpload'
            ]),
            loadNode(node, resolve) {
                axios.get(process.env.baseUrl + '/department/list', {params:{parentId:node.data.id||0}})
                    .then((ret)=>{
                        if(ret&&ret.data){
                            return resolve(ret.data.data);
                        }
                    })
            },
            handleAddCheckChange(data,checked) {
                if(checked) {
                    this.userDataForm.departmentId = data.id
                    this.treeDepartment.departmentName = data.name
                    this.treeDepartment.showTree = !this.treeDepartment.showTree
                    this.$refs.addTree.setCheckedKeys([])
                    this.$refs.addTree.setChecked(data,true)
                }

            },
            getOprateName(){
                this.oprateName = this.$router.currentRoute.params.name
            },
            delayMessage(msg)　{
                setTimeout(() => {
                    if(this.axiosCode === 0) {
                        this.$message({
                            type: 'success',
                            message: msg+'成功!'
                        });
                    }else{
                        this.$message.error(msg+'失败')
                    }
                },1000)
            },
            removeEmptyKey(obj) {
                let con = {}
                for (let key in obj) {
                    if (obj.hasOwnProperty(key) && obj[key]){
                        con[key] = obj[key]
                    }
                }
                return con;
            },
            formatDate() {
                this.userDataForm.birthday = getDate(returnDate(this.userDataForm.birthday),true)
            },
            validForm() {
                if(!validTel(this.userDataForm.phone)) {
                    this.$message.warning('请输入正确的手机号码');
                    return false;
                }
                if(this.userDataForm.email && !validEmail(this.userDataForm.email)) {
                    this.$message.warning('请输入正确的邮箱地址');
                    return false;
                }
                if(this.userDataForm.qq && !checkQQ(this.userDataForm.qq)) {
                    this.$message.warning('请输入正确的QQ号码');
                    return false;
                }
                return true
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //提交表单
                        if(!this.validForm()){
                            return false
                        }
                        if (this.oprateName === 'add') {
                            this.validNewUser({value: this.userDataForm.account}).then(response => {
                                if (!response.data.data) {
                                    this.addNewUserControl(this.removeEmptyKey(this.userDataForm)).then(response => {
                                        this.dealAxiosCode({val:response.data.code});
                                        this.$refs[formName].resetFields();
                                        this.treeDepartment.departmentName = '';
                                        this.delayMessage('添加');
                                        this.$router.push({path: '/power/user-control'});
                                    })
                                }
                                else{
                                    this.$message.error('添加失败，已存在的账号或手机号')
                                }
                            })
                        }
                        else {
                            this.editUserData(this.removeEmptyKey(this.userDataForm)).then(response => {
                                this.dealAxiosCode({val:response.data.code})
                                this.delayMessage('编辑');
                                this.$router.push({path: '/power/user-control'});
                            })
                        }
                    } else {
                        this.$message({
                            type: 'error',
                            message: '操作失败'
                        });
                        return false
                    }
                })
            },
            exitForm(formName) {
                this.$refs[formName].resetFields();
                this.$router.replace('/power/user-control');
            },
            uploadUserAvatarChange() {
                var _this = this
                var file = this.$refs.userAvatar.files[0]
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!file) {
                    this.$message.error('请选择要上传的图片!')
                    return;
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!')
                    return;
                }
                var reader = new FileReader()
                reader.readAsDataURL(file)
                reader.onloadend = function () {
                    _this.userDataForm.userAvatar = reader.result
                }

                var formData = new FormData()
                formData.append('file',file)
                formData.append('account',this.userDataForm.account);
                if (process.BROWSER_BUILD ) {
                    var token = window.localStorage.getItem('token');
                    formData.append('token',token);
                }
                this.userPhotoUpload(formData).then( response => {
                    this.dealAxiosCode({val:response.data.code})
                    this.delayMessage('图片上传')
                }).catch(error=>{
                })
            },
            treeBlurHide(){
                this.treeDepartment.showTree = false
            },
            getJobList() {
                this.$store.dispatch('getJobList')
            },
            getAddUserJob(val) {
                this.userDataForm.jobId = val[1]
            }
        },
        created() {
            setToken('parentUrl','userControlEdit');
            
            this.getOprateName()
            if (this.oprateName === 'edit') {
            	
                if(this.editIndex != null) {
                	
                    this.userDataForm = this.userDatas[this.editIndex];
                    this.formatDate() 
                    this.treeDepartment.departmentName = this.userDataForm.departmentId ? this.userDataForm.departmentName : '';
                    this.$store.commit('dealJobName',{data: this.userDataForm.jobName})
                }
                else{
                    this.$router.replace('/power/user-control')
                }
            }
            else {
                this.$store.commit('dealJobName',{data: ''});
                this.userDataForm = {
                    account: "",
                    name:"",
                    sex: "男",
                    birthday: "",
                    phone: "",
                    email: "",
                    qq: "",
                    jobId: "",
                    departmentId: "",
                    remark: "",
                    userAvatar: "",
                    code: ""
                }
            }
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.oprateName == 'edit' ? '编辑用户' : '添加用户';
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
            //获取岗位信息
            this.getJobList();
            
        }
    }


</script>

<style  lang="scss">
    .power-add-user{
        margin-top: 20px;
        .el-form-item.is-required .el-form-item__label:before{
            margin-right: 0;
        }
        .el-input,.el-textarea{
            width: 192px;
        }
        .add-oprate{
            text-align: center;
            padding: 0 20px;
            margin: 20px 0 30px;
            .save{
                margin-right: 20px;
            }
        }

        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            background-color: #ddd;
            vertical-align: middle;
            &:hover {
                 border-color: #20a0ff;
             }
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 120px;
            height: 120px;
            line-height: 120px;
            text-align: center;
        }
        .avatar-wraper{
            display: inline-block;
            width: 120px;
            height: 120px;
            position: relative;
            border-radius: 6px;
            transition: all .3s ease-in;
            cursor: pointer;
            overflow: hidden;
            background-color: #ddd;
            vertical-align: middle;
            text-align: center;
            &:hover{
                 background-color: #ccc;
             }
            .el-icon-plus{
                font-size: 28px;
                color: #8c939d;
                width: 120px;
                height: 120px;
                line-height: 120px;
                text-align: center;
            }
        }
        .avatar-contain{
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 1;
            background-color: white;
            line-height: 120px;
        }
        .avatar {
            display: inline-block;
            max-width: 100%;
            max-height: 100%;
            border: none;
            outline: none;
            vertical-align: middle;
        }
        .uploadUserAvatar{
            position: absolute;
            left: 0;
            top: 0;
            z-index: 10;
            width: 120px;
            height: 120px;
            opacity:0;
        }
        .upload-tips{
            display: inline-block;
            font-size: 12px;
            color: #999;
            margin-top: 106px;
        }
    }

</style>